package com.fast.develop.meta.base;

import com.fast.develop.meta.base.exception.MetaException;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 莫寅
 * @createTime 2022-06-04 23:41
 * @desc：
 */
@Slf4j
public class MetaConfiguration<T extends Meta> {


    private Map<String, List<T>> metaTypeModels = new HashMap<>();


    private Map<String, Map<String, T>> metaTypeTypeModels = new HashMap<>();

    private boolean initialized = false;

    private MetaRegistry metaRegistry;

    public MetaConfiguration() {
        this.metaRegistry = new MetaRegistry();
    }


    public MetaConfiguration register(MetaRegistor... metaRegistor){
        Arrays.stream(metaRegistor).forEach(metaRegistor1 -> metaRegistry.register(metaRegistor1));
        return this;
    }


    public MetaConfiguration build() {
        if(initialized){
            throw new MetaException("已初始化！");
        }

        metaRegistry.getMetaRegistors().stream().forEach(metaRegistor -> {
            List<T> metas = (List<T>) metaRegistor.getSchemaReader().read();
            metaTypeModels.put(metaRegistor.type(), metas);

            Map<String, T> metaMap = metas.stream().collect(Collectors.toMap(Meta::getId, t -> t));
            metaTypeTypeModels.put(metaRegistor.type(), metaMap);
        });

        initialized = true;

        return this;
    }

    public Map<String, T> getMetaModels(String metaType){
        return metaTypeTypeModels.get(metaType);
    }

    public void reload(){
        initialized = false;
        build();
    }

    public MetaRegistor getMetaRegistor(String type){
        return metaRegistry.getMetaRegistor(type);
    }

}
